package org.csu.canteen.controller;

import jakarta.servlet.http.HttpSession;
import org.csu.canteen.entity.*;
import org.csu.canteen.persistence.ItemMapper;
import org.csu.canteen.service.*;
import org.csu.canteen.service.Impl.AccountServiceImpl;
import org.csu.canteen.vo.AccountVO;
import org.csu.canteen.vo.ItemVO;
import org.csu.canteen.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;
    @Autowired
    private CartItemService cartItemService;
    @Autowired
    private CouponService couponService;

    @Autowired
    private CatalogService catalogService;
    @Autowired
    private LogService logService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private AccountServiceImpl accountService;
    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    public CartController(CartService cartService, CartItemService cartItemService, CouponService couponService) {


    }

    /**
     * 进入购物车页面
     */
    @GetMapping("/cartForm")
    public String viewCart(@RequestParam String username,HttpSession session,
                           @RequestParam(value = "selectedCouponId", required = false) Integer selectedCouponId,
                           Model model) {
        // 1. 获取当前用户信息
        AccountVO loginAccount = accountService.getAccountByUsername(username);
        Cart cart = (Cart) session.getAttribute("cart");
        // 2. 查询 cartitem 表，获取购物车商品列表
        List<CartItem> cartItems = cart.getCartItemList();

// 3. 查询 item 表，把 item 关联到 cartItem
        Map<String, Item> itemMap = itemService.getItemMapByItemIds(
                cartItems.stream().map(CartItem::getItemId).collect(Collectors.toList())
        );
        for (CartItem cartItem : cartItems) {
            cartItem.setItem(itemMap.get(cartItem.getItemId()));
        }

// 4. 查询 product 表，把 product 关联到 item
        Map<String, ProductVO> productVOMap = catalogService.getAllProducts().stream()
                .collect(Collectors.toMap(ProductVO::getProductId, Function.identity()));

        for (Item item : itemMap.values()) {
            item.setProductVO(productVOMap.get(item.getProductId())); // 假设 Item 有 setProduct 方法
        }
        // 5. 计算购物车总价
        BigDecimal subTotal = cartItems.stream()
                .filter(item -> item.getItem() != null) // 确保 item 不是 null
                .map(item -> item.getItem().getListPrice().multiply(BigDecimal.valueOf(item.getQuantity()))) // 单价 * 数量
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 6. 查询用户优惠券
        List<CouponPackage> couponPackages = couponService.searchCouponByUsername(username).getCouponList();
        List<Coupon> couponList = couponPackages.stream()
                .map(couponPackage -> couponService.searchCouponByID(couponPackage.getCouponId()))
                .toList();

        // 7. 传递数据到前端
        model.addAttribute("products", productVOMap);
        model.addAttribute("cartItems", cartItems);
        model.addAttribute("subTotal", subTotal);
        model.addAttribute("couponList", couponList);
        model.addAttribute("selectedCouponId", selectedCouponId);
        model.addAttribute("loginAccount", loginAccount);  // 传递 loginAccount

        return "cart/cart";
    }

    @GetMapping("/addItem")
    public String addItemToCart(@RequestParam("workingItemId") String workingItemId, HttpSession session, Model model) {
        System.out.println(workingItemId);
        AccountVO loginAccount = (AccountVO) session.getAttribute("loginAccount");
        System.out.println(loginAccount);
        if (loginAccount == null) {
            model.addAttribute("signOnMsg", "还未登录，请先登录！");
            return "account/signon";
        }

        Cart cart = (Cart) session.getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
        }

        if (cart.containsItemId(workingItemId)) {
            //若item在购物车里，就只要更改数量
            cart.incrementQuantityByItemId(workingItemId);
        } else {
            boolean isInStock = catalogService.isItemInStock(workingItemId);
            ItemVO itemVO = catalogService.getItem(workingItemId);
            Item item =itemMapper.selectById(itemVO.getItemId());
            cart.addItem(item, isInStock);
        }


            for (CartItem cartItem : cart.getCartItemList()) {
                cartItemService.insertItem(cartItem, loginAccount.getUsername());
                System.out.println(cartItem);
                System.out.println(cartItem.getItemId());
                System.out.println(cartItem.getUsername());

                Log log = createLog(cartItem.getItem(), loginAccount);
                logService.recordLog(log);
                System.out.println("log: " + log.getMark());
            }

        session.setAttribute("cart", cart);
        return "redirect:/cart/cartForm?username=" + loginAccount.getUsername();
    }

    private Log createLog(Item item, AccountVO account) {
        Log log = new Log();
        log.setDate(new Date());
        log.setName(item.getProductId());
        log.setUsername(account.getUsername());
        log.setMark(1); // 添加到购物车
        return log;
    }
    /**
     * 更新购物车商品数量
     */
    @PostMapping("/updateCart")
    public String updateCart(@RequestParam("username") String username,
                             @RequestParam("itemId") int itemId,
                             @RequestParam("quantity") int quantity) {
        if (cartService.checkStock(itemId, quantity)) {
            CartItem cartItem = new CartItem();
            cartItem.setItemId(String.valueOf(itemId));
            cartItem.setNumber(quantity);
            cartItemService.insertItem(cartItem, username);
        }
        return "redirect:/cart/cartForm?username=" + username;
    }

    /**
     * 移除购物车中的商品
     *  @GetMapping("/removeCartItem")
     *     public String removeCartItem(@RequestParam("username") String username,
     *                                  @RequestParam("itemId") int itemId) {
     *         CartItem cartItem = new CartItem();
     *         cartItem.setItemId(String.valueOf(itemId));
     *         cartItemService.removeItem(cartItem);
     *         return "redirect:/cart/cartForm?username=" + username;
     *     }
     */



    @GetMapping("/clean")
    public String cleanCart(HttpSession session) {
        session.setAttribute("cart", new Cart()); // 直接创建新的购物车对象
        return "redirect:/catalog/index"; // 返回 Thymeleaf 视图
    }
    /**
     * 选择优惠券
     */
    @PostMapping("/applyCoupon")
    public String applyCoupon(@RequestParam("username") String username,
                              @RequestParam("couponId") int couponId,
                              Model model) {
        List<CartItem> cartItems = cartItemService.getCartByUsername(username);
        BigDecimal subTotal = cartItems.stream()
                .map(item -> cartService.getSubTotal(null, item.getItem()))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        Coupon coupon = couponService.searchCouponByID(couponId);
        if (coupon != null && coupon.getLimit() != null && BigDecimal.valueOf(coupon.getLimit()).compareTo(subTotal) <= 0) {
            if (coupon.getDeduction() != 0) {
                subTotal = subTotal.subtract(BigDecimal.valueOf(coupon.getDeduction()));
            }
            if (coupon.getDiscount() != 0) {
                subTotal = subTotal.multiply(BigDecimal.valueOf(coupon.getDiscount()));
            }
        }

        // **存入选中的优惠券 ID**
        model.addAttribute("selectedCouponId", couponId);

        model.addAttribute("discountedSubTotal", subTotal.doubleValue());
        return "redirect:/cart/cartForm?username=" + username;
    }
    /**
     * 进入结算页面
     */
    @GetMapping("/checkoutForm")
    public String checkout(@RequestParam("username") String username,HttpSession session, Model model) {

        // 1. 获取当前用户信息
        AccountVO loginAccount = accountService.getAccountByUsername(username);

        Cart cart = (Cart) session.getAttribute("cart");
        // 2. 查询 cartitem 表，获取购物车商品列表
        List<CartItem> cartItems = cart.getCartItemList();

// 3. 查询 item 表，把 item 关联到 cartItem
        Map<String, Item> itemMap = itemService.getItemMapByItemIds(
                cartItems.stream().map(CartItem::getItemId).collect(Collectors.toList())
        );
        for (CartItem cartItem : cartItems) {
            cartItem.setItem(itemMap.get(cartItem.getItemId()));
        }


        if (cartItems.isEmpty()) {
            return "redirect:/cart/cartForm?username=" + username;
        }

        // 4. 查询 product 表，把 product 关联到 item
        Map<String, ProductVO> productVOMap = catalogService.getAllProducts().stream()
                .collect(Collectors.toMap(ProductVO::getProductId, Function.identity()));

        for (Item item : itemMap.values()) {
            item.setProductVO(productVOMap.get(item.getProductId())); // 假设 Item 有 setProduct 方法
        }

        // 5. 计算购物车总价
        BigDecimal subTotal = cartItems.stream()
                .filter(item -> item.getItem() != null) // 确保 item 不是 null
                .map(item -> item.getItem().getListPrice().multiply(BigDecimal.valueOf(item.getQuantity()))) // 单价 * 数量
                .reduce(BigDecimal.ZERO, BigDecimal::add);



        model.addAttribute("products", productVOMap);
        model.addAttribute("cart", cart);  // ✅ 传递 cart 到前端
        model.addAttribute("cartItems", cartItems);
        model.addAttribute("subTotal", subTotal);
        return "cart/checkout";
    }
}